<template>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="close">
        <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="父级角色" prop="parent_id">

                <el-cascader ref="elcascader" placeholder="请选择父级"
                             @visible-change="elCascaderOnlick"
                             @expand-change="elCascaderOnlick"
                             @change="regionHandleChange"
                             v-model="selectedOptions"
                             :props="{ checkStrictly: true, expandTrigger: 'hover' }"
                             :options="role_list">
                </el-cascader>
            </el-form-item>
            <el-form-item label="角色名称"><el-input v-model="form.role_name" :autosize="{ minRows: 2, maxRows: 20}" placeholder="角色名称"/></el-form-item>
            <el-form-item label="备注"><el-input v-model="form.role_remarks" :autosize="{ minRows: 2, maxRows: 100}" type="textarea" placeholder="备注"/></el-form-item>
            <el-form-item label="是否启用" prop="is_check">
                <el-radio-group v-model="form.is_check">
                    <el-radio :label="0" :checked="form.is_check == 0 ? 'checked' : ''">禁用</el-radio>
                    <el-radio :label="1" :checked="form.is_check == 1 ? 'checked' : ''">启用</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <div style="text-align:right;">
            <el-button type="danger" @click="close">取 消</el-button>
            <el-button type="primary" @click="save">确 定</el-button>
        </div>
    </el-dialog>
</template>

<script>
    export default {
        name: 'AdminRoleDetail',
        data() {
            return {
                form: {
                    parent_id: 0,
                    role_name: '',
                    role_remarks: '',
                    is_check: 0,
                },
                role_list:[],
                role_ids: [],
                select_role_name: '',
                selectedOptions:[],
                rules: {
                    account: [
                        {required: true, trigger: 'blur', message: '请输入管理员账户'},
                    ],
                },
                title: '',
                dialogFormVisible: false,
            }
        },
        watch: {
            filterText(val) {
                this.$refs.tree.filter(val);
            }
        },
        created() {
            // 获取菜单列表
            this.getRolesSelect()
        },
        methods: {
            // 获取选中的数据，进行赋值操作
            regionHandleChange(arr) {
                // arr是选中的数组eg:[1, 5]，但因为后台数据库设计暂时不支持数组传参，后台只要选中的节点的值，所以我将数组最后一个值取出来进行赋值操作
                // 注意：这里要传的值相当于id，父子节点都是唯一的
                if (arr) {
                    // 此方法返回的是一个元素，eg:5
                    this.form.parent_id = arr[arr.length - 1];
                }
            },

            filterNode(value, data) {
                if (!value) return true;
                return data.label.indexOf(value) !== -1;
            },
            toggleShow() {
                this.show = !this.show;
            },
            // 获取菜单列表
            async getRolesSelect() {
                const {data} = await this.$get(this.$api.adminRoles+this.$api.getSelectLists,{type:1,role_id:this.form.role_id});
                this.role_list = data;
                console.log('role_list')
                console.log(this.role_list)
            },
            // 触发click事件，关闭下拉框
            elCascaderOnlick() {
                let that = this;
                // .el-cascader-node__label 和 .el-cascader-panel .el-radio 这是Element级联选择器的类，可以参考下方截图
                setTimeout(function() {
                    document.querySelectorAll(".el-cascader-node__label").forEach((el) => {
                        el.onclick = function() {
                            this.previousElementSibling.click();
                            // 选中span标签后，关闭下拉框
                            that.$refs.elcascader.dropDownVisible = false;
                        };
                    });
                    document.querySelectorAll(".el-cascader-panel .el-radio")
                        .forEach((el) => {
                            el.onclick = function() {
                                // 选中radio后，关闭下拉框
                                that.$refs.elcascader.dropDownVisible = false;
                            };
                        });
                }, 100);
            },
            showEdit(row, rolelist,i) {
                const detail = Object.assign({}, row);
                console.log('弹出')
                console.log(row)
                console.log(rolelist)
                console.log(detail)
                this.role_ids = rolelist
                if (!detail) {
                    this.title = '添加';
                } else {
                    if (i==1){
                        this.title = '编辑';
                        this.form = Object.assign(this.form, detail);
                        if (detail.roles) {
                            for (const key in detail.roles) {
                                this.form.role_ids.push(detail.roles[key].role_id);
                            }
                        }
                    } else {
                        this.title = "添加子菜单";
                        this.form.role_id = detail.role_id
                        if (detail.parent_id!=0){
                            this.selectedOptions =[row.parent_id,row.role_id]
                        } else {
                            this.selectedOptions =[row.role_id]
                        }
                    }


                    this.title = '编辑';
                    this.form = Object.assign(this.form, detail);
                    if (detail.roles) {
                        for (const key in detail.roles) {
                            this.form.role_ids.push(detail.roles[key].role_id);
                        }
                    }
                }
                this.dialogFormVisible = true
            },

            close() {
                this.$refs['form'].resetFields();
                this.form = this.$options.data().form;
                this.dialogFormVisible = false;
            },
            save() {
                this.$refs['form'].validate(async (valid) => {
                    if (valid) {
                        const {msg, status} = this.form.role_id ?
                            await this.$put(this.$api.adminRoles+this.$api.update,this.form) :
                            await this.$post(this.$api.adminRoles+this.$api.create,this.form) ;
                        this.$message({
                            message: msg,
                            type: status == 1 ? 'success' : 'error',
                        });
                        this.$emit('fetchData');
                        this.close();
                    } else {
                        return false;
                    }
                })
            }
        }
    }
</script>


<style scoped>
    .el-form-item > labe {
        width: 100px;
    }

    label.el-checkbox {
        display: block;
    }

    #img-btn {
        position: absolute;
        bottom: 15px;
        margin-left: 40px;
    }
</style>
